﻿using SK3000RunningTestTool.SKServerDelegate;
using SK3000RunningTestTool.SKServerEnum;
using SK3000RunningTestTool.SKServerSource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using WebSocketSharp;

namespace SK3000RunningTestTool.SKService
{
    public class Service_WebSocket : ISKService
    {
        private const string c_strTestHBCmd = "{\"cmd\":\"HB\",\"t\":1547692387}'";
        ServiceTestCompleteValue result;
        bool bolFlag = false;
        public SKServer Server
        {
            get;
            set;
        }
        public int ID
        {
            get;
            set;
        }
        private Enum_ServiceTestType typeID = Enum_ServiceTestType.TCPService;
        /// <summary>
        /// 类型ID
        /// </summary>
        public Enum_ServiceTestType TypeID
        {
            get { return typeID; }
            set { }
        }
        public ServiceTestType Type => ServiceTestTypeSource.ServiceTestTypeList[typeID];
        string strServiceName = "客户端服务";
        public string ServiceName
        {
            get { return strServiceName; }
            set { strServiceName = value; }
        }

        public string ServiceRemark
        {
            get;
            set;
        }
        public string ServiceAddress
        {
            get;
            set;
        }

        public ushort ServicePort
        {
            get;
            set;
        }

        public object Tag
        {
            get;
            set;
        }

        public event ServiceTestProgressDelegate ServiceTestProgressEvent;

        private void ServiceTestProgress(ServiceTestProgressValue value)
        {
            if (ServiceTestProgressEvent != null)
            {
                ServiceTestProgressEvent(this, value);
            }
        }



        public event ServiceTestCallbackDelegate ServiceTestCallbackEvent;

        public void ServiceTestCallback(ServiceTestCallbackValue value)
        {
            if (ServiceTestCallbackEvent != null)
            {
                ServiceTestCallbackEvent(this, value);
            }
        }


        /// <summary>
        /// 服务器测试 
        /// </summary>
        /// <returns></returns>
        public ServiceTestCompleteValue ServiceTest()
        {
            ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.ServiceTestStart });
            ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.ConnectServiceing });
            ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 0 });
            result = new ServiceTestCompleteValue
            {
                reuslt = Enum_ServiceTestResult.Fail,
            };
            //转警服务器服务器测试
            //测试条目 1. 连接服务器端口
            var ws = new WebSocket(ServiceAddress);
            ws.OnMessage += Ws_OnMessage;
            ws.OnError += Ws_OnError;
            ws.OnClose += Ws_OnClose;
            ws.OnOpen += Ws_OnOpen;
            ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 10 });
            ws.Connect();

            ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 30 });
            if (ws.ReadyState != WebSocketState.Open)
            {
                ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 40 });
                //连接异常
                ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.ConnectException });
                result = new ServiceTestCompleteValue
                {
                    reuslt = Enum_ServiceTestResult.TestException,
                    Para1="服务连接失败"
                };
                ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 80 });
                bolFlag = true;
            }
            else
            {
                //连接正常，通过 Ws_OnMessage 触发成功
                ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 35 });
                ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.ConnectSuccess });
                ServiceTestCallback(new ServiceTestCallbackValue
                {
                    EventValue = Enum_ServiceTestEvent.SendTestDataing,
                    EventMessage = "发送数据:" + c_strTestHBCmd
                });

                ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 40 });
                ws.Send(c_strTestHBCmd);
                ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 50 });
            }
            //测试条目 2. 发送登陆数据
            while (!bolFlag)
            {
                CommonMethod.Common.Delay_Millisecond(50);
            }
            WsClose(ws);
            bolFlag = false;
            ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 100 });
            ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.ServiceTestEnd });
            return result;
        }

        private void Ws_OnOpen(object sender, EventArgs e)
        {
            //连接成功,发送心跳数据
            WebSocket ws = (WebSocket)sender;
        }

        private void Ws_OnClose(object sender, CloseEventArgs e)
        {
            //ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.ServiceTestEnd });
        }

        private void Ws_OnError(object sender, ErrorEventArgs e)
        {
            result = new ServiceTestCompleteValue
            {
                reuslt = Enum_ServiceTestResult.TestException,
                Para1 = e.Message.ToString()
            };
            WebSocket ws = (WebSocket)sender;
            WsClose(ws);
            bolFlag = true;
        }

        private void Ws_OnMessage(object sender, MessageEventArgs e)
        {
            ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 70 });
            ServiceTestCallback(new ServiceTestCallbackValue
            {
                EventValue = Enum_ServiceTestEvent.SendTestDataSuccess,
                EventMessage = "收到返回数据:" + e.Data
            });
            WebSocket ws = (WebSocket)sender;
            result = new ServiceTestCompleteValue
            {
                reuslt = Enum_ServiceTestResult.Normal,
            };

            ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 80 });
            bolFlag = true;
        }

        private bool  WsClose(WebSocket ws )
        {
            bool bolResult = false;
            ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.ConnectCloseing });
            if (ws.IsAlive)
            {
                ws.Close();
            }
            ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.ConnectClosed});
            return bolResult;
        }

        public void ServiceTestAsync(ServiceTestCompleteDelegate callback)
        {
            Timer timTimeOutVideoClose = new Timer(new TimerCallback(timTimtOutVideoClose_Event), callback, 0, Timeout.Infinite);
            return;
        }

        private void timTimtOutVideoClose_Event(object sender)
        {
            ServiceTestCompleteValue value = ServiceTest();
            ServiceTestCompleteDelegate call = (ServiceTestCompleteDelegate)sender;
            if (call != null)
            {
                call(this, value);
            }
        }
    }
}
